package com.example.androiddemo.day714;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.example.androiddemo.R;

public class ServiceActivity extends AppCompatActivity implements View.OnClickListener {

    private Button mPlayMusic, mStopMusic;
    private MusicService.MusicBinder mMusicService;
    private Intent intent;
    private int count = 0;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("====================", "与服务建立连接成功");
            mMusicService = (MusicService.MusicBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("====================", "关闭与服务的连接");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        initView();
        intent = new Intent(this, MusicService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
    }


    private void initView() {
        mPlayMusic = findViewById(R.id.play_music);
        mStopMusic = findViewById(R.id.stop_music);
        mPlayMusic.setOnClickListener(this);
        mStopMusic.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_music:
                mMusicService.startMusic();
                count = 0;
                break;
            case R.id.stop_music:
                mMusicService.stopMusic();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
        Log.i("=============", "音乐播放界面被销毁");
    }

}